package com.lonni.rpc.core.spring;

import com.lonni.rpc.core.annotation.EnableRpc;
import com.lonni.rpc.core.annotation.RpcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.stereotype.Component;

/**
 * rpc bean注册器
 * 将标识RpcService注解的类添加到spring容器中
 * 依赖 RpcSpringScanner
 *  参考 https://blog.csdn.net/a294634473/article/details/100728363
 * @author: lonni
 * @CreateTime: 2024-06-27  22:41
 * @Description:
 */
@Slf4j
public class RpcSpringRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
    /**
     * 扫描包的属性名称
     */
    private final static String SCAN_FILED = "basePackage";
    private ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    /**
     * 具体的注册逻辑
     *
     * @param importingClassMetadata
     * @param registry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {

        AnnotationAttributes rpcScanAnnotationAttributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(EnableRpc.class.getName()));
        if (rpcScanAnnotationAttributes == null) {
            return;
        }
        String[] basePackages = rpcScanAnnotationAttributes.getStringArray("basePackage");
        if (basePackages.length == 0) {
            basePackages = new String[]{((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass().getPackage().getName()};
        }
        com.lonni.rpc.core.spirng.RpcSpringScanner rpcSpringScanner = new com.lonni.rpc.core.spirng.RpcSpringScanner(registry, RpcService.class);
        com.lonni.rpc.core.spirng.RpcSpringScanner springBeanScanner = new com.lonni.rpc.core.spirng.RpcSpringScanner(registry, Component.class);

        if (resourceLoader != null) {
            rpcSpringScanner.setResourceLoader(resourceLoader);
            //增加扫描被Component注解的类
//            springBeanScanner.setResourceLoader(resourceLoader);
        }
        int rpcServiceCount = rpcSpringScanner.scan(basePackages);
//        int springCount = springBeanScanner.scan(basePackages);
        log.info("rpcServiceScanner扫描的数量 [{}],springbean数量:", rpcServiceCount);

    }
}
